
################## REPLICATION SCRIPT #################################### 
################## Mapping Unionism in Latin America: A Proposal for Measuring Union Power
################## Rodrigo M. Medel and Sebastián Osorio Lavin
################## doi:10.1017/lap.2025.10018


library(haven)
library(stats)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(ggpubr)
library(readstata13)
library(psych)
library(stargazer)

# NOTE: Original database and codebook is also available in https://doi.org/10.7910/DVN/7GV4FA, Harvard Dataverse, V1
# NOTE: To cite the database please use:  Somma, Nicolás M.; Medel, Rodrigo M.; Disi, Rodolfo; Bargsted, Matías; Cavieres, Julia; Candia, Fernando; González, Andrés; Karle, Cristóbal; Osorio, Sebastián; Sáez, Rocío; Selamé, Nicolás, 2025, "MovLab: Labor Movements in Latin America", https://doi.org/10.7910/DVN/7GV4FA, Harvard Dataverse, V1




# 1. Reading the data --------

base.labor=read.csv("/Users/rodrimedel/Desktop/Papers Medel/Poder sindical/Dataverse/MovLab 1.0 (2025).csv", dec=",", sep=";")
options(max.print=9999)

#Dejar todas las variables como numéricas, con excepción de año y país


base.labor = base.labor %>%
  mutate(across(-c(anio, pais, presidente_mandato), ~ as.numeric(as.factor(.))))


base.labor$pais=as.factor(base.labor$pais)
levels(base.labor$pais)

# 2. Associative power index ---------------------------------------------------

# Material Resources

base.labor$C1_acciones_r <- recode(base.labor$C1_acciones, `1` = 3, `2` = 2, `3` = 1)
base.labor$C2_pensiones_r <- recode(base.labor$C2_pensiones, `1` = 3, `2` = 2, `3` = 1)
base.labor$C3_inmuebles_r <- recode(base.labor$C3_inmuebles, `1` = 3, `2` = 2, `3` = 1)
base.labor$C4_fondos_r <- recode(base.labor$C4_fondos, `1` = 3, `2` = 2, `3` = 2, `4` = 1)
base.labor$C5_medios_r <- recode(base.labor$C5_medios, `1` = 3, `2` = 2, `3` = 1)
base.labor$C6_cooperat_r <- recode(base.labor$C6_cooperat, `1` = 3, `2` = 2, `3` = 1)


# normalize data (Min-Max)
normalize_min_max <- function(x) {
  return((x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE)))
}

base.labor$C2_pensiones_norm <- normalize_min_max(base.labor$C2_pensiones_r)
base.labor$C3_inmuebles_norm <- normalize_min_max(base.labor$C3_inmuebles_r)
base.labor$C4_fondos_norm <- normalize_min_max(base.labor$C4_fondos_r)
base.labor$C5_medios_norm <- normalize_min_max(base.labor$C5_medios_r)
base.labor$C6_cooperat_norm <- normalize_min_max(base.labor$C6_cooperat_r)


# Creation of the index
base.labor$indice_materiales <- rowMeans(cbind(base.labor$C2_pensiones_norm, 
                                               base.labor$C3_inmuebles_norm,
                                               base.labor$C5_medios_norm,
                                               base.labor$C6_cooperat_norm), na.rm = TRUE)

table(base.labor$indice_materiales)


# Organization and movilization capacity 


base.labor$A3_cohsin_norm <- normalize_min_max(base.labor$A3_cohsin)
base.labor$A5_nacsin_norm <- normalize_min_max(base.labor$A5_nacsin)
base.labor$A6_exporg_norm <- normalize_min_max(base.labor$A6_exporg)
base.labor$A4_capmov_norm <- normalize_min_max(base.labor$A4_capmov)
base.labor$A2_poasoc_norm <- normalize_min_max(base.labor$A2_poasoc)



poder_asociativo=subset(base.labor, select=c(A2_poasoc_norm,
                                             A4_capmov_norm,
                                             A6_exporg_norm,
                                             indice_materiales))
alpha(poder_asociativo)


base.labor$Poder_Asociativo=rowMeans(cbind(base.labor$A4_capmov_norm,
                                           base.labor$A2_poasoc_norm,
                                           base.labor$A6_exporg_norm,
                                           base.labor$indice_materiales), na.rm = TRUE)


tabla=base.labor%>%dplyr::group_by(anio, pais)%>%dplyr::summarize(promedio=mean(Poder_Asociativo,na.rm = TRUE))

tabla


ggplot(tabla, aes(x=anio , y=promedio))+
  geom_line(size = 1, alpha = .8) +
  theme_classic() +
  scale_x_continuous(
    expand = c(0, 2),
    limits = c(1990, 2020), 
    breaks = seq(1990, 2020, by = 5)) + theme_pubr() + 
  theme(axis.text.x=element_text(angle = 90,vjust = 0.5, hjust = 1,
                                 size = 16, color="black"),
        axis.text.y=element_text(angle = 0,vjust = 0.5, hjust = 1,
                                 size = 10, color="black"),
        axis.title.y = element_text(color="black", size=16),
        axis.title.x = element_text(color="black", size=16),
        legend.position = "top", legend.text = element_text(size=16, color="black"),
        panel.grid.minor.y=element_blank(),
        panel.grid.major=element_line(color = "grey30", size = .05),panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank()) +
  scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, by = 0.2)) +
  ggtitle("Evolution of associative power in Latin America",
          subtitle = "1990-2020 for 17 countries in L.A") +
  labs(x = "Year", y = "Average associative power", caption = "Rodrigo Medel") + facet_wrap(~pais)


# 3. Structural power index ----------------------------------------------------

base.labor$B2_poestruc1_norm <- normalize_min_max(base.labor$B2_poestruc1)
base.labor$B4_poestruc2_norm <- normalize_min_max(base.labor$B4_poestruc2)
base.labor$B6_poestruc3_norm <- normalize_min_max(base.labor$B6_poestruc3)
base.labor$B11_secpub_norm <- normalize_min_max(base.labor$B11_secpub)
base.labor$B12_poestruc_gen_norm <- normalize_min_max(base.labor$B12_poestruc_gen)


poder_estructural=subset(base.labor, select=c(B2_poestruc1_norm,
                                              B4_poestruc2_norm, 
                                              B6_poestruc3_norm,
                                              B12_poestruc_gen_norm))


alpha(poder_estructural)


maximos_por_mandato <- base.labor %>%
  group_by(pais, presidente_mandato, numero_mandato) %>%
  summarise(
    Estructural_Sector1 = max(B2_poestruc1_norm, na.rm = TRUE),
    Estructural_Sector2 = max(B4_poestruc2_norm, na.rm = TRUE),
    Estructural_Sector3 = max(B6_poestruc3_norm, na.rm = TRUE),
    Estructural_General=max(B12_poestruc_gen_norm, na.rm=TRUE),
    .groups = 'drop'  # Esto elimina la agrupación una vez finalizada la suma
  )

maximos_por_mandato


base.labor <- base.labor %>%
  left_join(maximos_por_mandato, by = c("pais", "presidente_mandato", "numero_mandato"))



poder_estructural=subset(base.labor, select=c(Estructural_Sector1,
                                              Estructural_Sector2,
                                              Estructural_Sector3, 
                                              Estructural_General))


alpha(poder_estructural)



base.labor$Poder_Estructural=rowMeans(cbind(base.labor$Estructural_Sector1,
                                            base.labor$Estructural_Sector2,
                                            base.labor$Estructural_Sector3,
                                            base.labor$Estructural_General), na.rm = TRUE)

table(base.labor$Poder_Estructural)
tabla=base.labor%>%dplyr::group_by(pais,anio)%>%dplyr::summarise(promedio=mean(Poder_Estructural,na.rm = TRUE))

tabla


ggplot(tabla, aes(x=anio , y=promedio))+
  geom_line(size = 1, alpha = .8) +
  theme_classic() +
  scale_x_continuous(
    expand = c(0, 2),
    limits = c(1990, 2020), 
    breaks = seq(1990, 2020, by = 5)) + theme_pubr() + 
  theme(axis.text.x=element_text(angle = 90,vjust = 0.5, hjust = 1,
                                 size = 16, color="black"),
        axis.text.y=element_text(angle = 0,vjust = 0.5, hjust = 1,
                                 size = 10, color="black"),
        axis.title.y = element_text(color="black", size=16),
        axis.title.x = element_text(color="black", size=16),
        legend.position = "top", legend.text = element_text(size=16, color="black"),
        panel.grid.minor.y=element_blank(),
        panel.grid.major=element_line(color = "grey30", size = .05),panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank()) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.2)) +
  ggtitle("Evolution of structural power in Latin America",
          subtitle = "1990-2020 for 17 countries in L.A.") +
  labs(x = "Year", y = "Average structural power", caption = "Rodrigo Medel") + facet_wrap(~pais)




# 4. Social power index --------------------------------------------------------

table(base.labor$J4_campesinos)

base.labor$J1_pocol_norm <- normalize_min_max(base.labor$J1_pocol)
base.labor$J11_pobladores_norm <- normalize_min_max(base.labor$J11_pobladores)
base.labor$J2_indigenas_norm <- normalize_min_max(base.labor$J2_indigenas)
base.labor$J4_campesinos_norm <- normalize_min_max(base.labor$J4_campesinos)




poder_social=subset(base.labor, select=c(J11_pobladores_norm, 
                                         J2_indigenas_norm,
                                         J4_campesinos_norm ))

alpha(poder_social)

base.labor$poder_social=rowMeans(cbind(base.labor$J11_pobladores_norm, 
                                       base.labor$J2_indigenas_norm,
                                       base.labor$J4_campesinos_norm), na.rm = TRUE)


tabla=base.labor%>%dplyr::group_by(anio, pais)%>%dplyr::summarize(promedio=mean(poder_social,na.rm = TRUE))

tabla



ggplot(tabla, aes(x=anio , y=promedio))+
  geom_line(size = 1, alpha = .8) +
  theme_classic() +
  scale_x_continuous(
    expand = c(0, 2),
    limits = c(1990, 2020), 
    breaks = seq(1990, 2020, by = 5)) + theme_pubr() + 
  theme(axis.text.x=element_text(angle = 90,vjust = 0.5, hjust = 1,
                                 size = 16, color="black"),
        axis.text.y=element_text(angle = 0,vjust = 0.5, hjust = 1,
                                 size = 10, color="black"),
        axis.title.y = element_text(color="black", size=16),
        axis.title.x = element_text(color="black", size=16),
        legend.position = "top", legend.text = element_text(size=16, color="black"),
        panel.grid.minor.y=element_blank(),
        panel.grid.major=element_line(color = "grey30", size = .05),panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank()) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.2)) +
  ggtitle("Evolution of social power in Latin America",
          subtitle = "1990-2020 for 17 countries in L.A.") +
  labs(x = "Year", y = "Average social power", caption = "Rodrigo Medel") + facet_wrap(~pais)




# 5. Institutional power index ------------------------------------------------



base.labor$I17_participacion[base.labor$I17_participacion==4]=1



base.labor$I13_afgob_norm= normalize_min_max(base.labor$I13_afgob)
base.labor$I17_participacion_norm <- normalize_min_max(base.labor$I17_participacion)
base.labor$I12_relep_norm <- normalize_min_max(base.labor$I12_relep)
base.labor$I19_respuesta_norm = normalize_min_max(base.labor$I19_respuesta)

poder_inst=subset(base.labor, select=c(I13_afgob_norm,
                                       I17_participacion_norm, 
                                       I12_relep_norm,
                                       I19_respuesta_norm))

alpha(poder_inst)


base.labor$Poder_Inst=(base.labor$I13_afgob_norm +  base.labor$I19_respuesta_norm + base.labor$I12_relep_norm +
                         base.labor$I17_participacion_norm)/4
table(base.labor$Poder_Inst)

library(dplyr)
tabla=base.labor%>%dplyr::group_by(anio,pais)%>%dplyr::summarise(promedio=mean(Poder_Inst,na.rm = TRUE))


ggplot(tabla, aes(x=anio , y=promedio))+
  geom_line(size = 1, alpha = .8) +
  theme_classic() +
  scale_x_continuous(
    expand = c(0, 2),
    limits = c(1990, 2020), 
    breaks = seq(1990, 2020, by = 5)) + theme_pubr() + 
  theme(axis.text.x=element_text(angle = 90,vjust = 0.5, hjust = 1,
                                 size = 16, color="black"),
        axis.text.y=element_text(angle = 0,vjust = 0.5, hjust = 1,
                                 size = 10, color="black"),
        axis.title.y = element_text(color="black", size=16),
        axis.title.x = element_text(color="black", size=16),
        legend.position = "top", legend.text = element_text(size=16, color="black"),
        panel.grid.minor.y=element_blank(),
        panel.grid.major=element_line(color = "grey30", size = .05),panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank()) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.2)) +
  ggtitle("Evolution of institutional power in Latin America",
          subtitle = "1990-2020 for 17 countries in L.A.") +
  labs(x = "Year", y = "Average institutional power", caption = "Rodrigo Medel") + facet_wrap(~pais)




# 6. Factor analysis ------------------------------------------------------------


sub.base=subset(base.labor, select=c(A2_poasoc_norm,
                                     A6_exporg_norm,
                                     A4_capmov_norm,
                                     indice_materiales,
                                     Estructural_Sector1,
                                     Estructural_Sector2,
                                     Estructural_Sector3, 
                                     Estructural_General,
                                     J11_pobladores_norm, 
                                     J2_indigenas_norm,
                                     J4_campesinos_norm,
                                     I13_afgob_norm,
                                     I17_participacion_norm, 
                                     I12_relep_norm,
                                     I19_respuesta_norm))


matriz=cor(sub.base, use="complete.obs")
matriz

base=scale(sub.base)
base=as.data.frame(base)
stargazer(base, type="text")

parallel= fa.parallel(base, n.obs=nrow(sub.base), 
                      fm = 'minres',fa="fa", n.iter=100, 
                      main="Scree plots with parallel analysis", cor= "cor")



obs = data.frame(parallel$fa.values) 
obs$type = c('Observed data') 
obs$num = c(row.names(obs)) 
obs$num = as.numeric(obs$num) 
colnames(obs) = c('eigenvalue', 'type', 'num')

#Creo datos 
sim = data.frame(parallel$fa.sim) 
sim$type = c('Simulated data') 
sim$num = c(row.names(obs)) 
sim$num = as.numeric(sim$num) 
colnames(sim) = c('eigenvalue', 'type', 'num')

eigendat = rbind(obs,sim)

apatheme=theme_bw()+ 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.title=element_blank(),
        legend.position=c(.86,.88), axis.line.x = element_line(color='black'),
        axis.line.y = element_line(color='black'),
        legend.box.background = element_rect(colour = "black"))

p = ggplot(eigendat, aes(x=num, y=eigenvalue, shape=type)) + 
  geom_line()+ geom_point(size=4)+ scale_y_continuous(name='Eigenvalue')+
  scale_x_continuous(name='Number of factors', breaks=min(eigendat$num):max(eigendat$num))+ 
  scale_shape_manual(values=c(16,1)) + geom_vline(xintercept = 4.5, linetype = 'dashed')+ 
  apatheme 
p

varimax.factors <- fa(sub.base, fm = "ml", nfactors = 4,
                      rotate =  "varimax",  residuals = TRUE, 
                      scores = "regression", cor="cor")
print(varimax.factors$loadings, cutoff =0.4) 
varimax.factors$loadings


library(sjPlot)
library(webshot)

tab_fa(sub.base, rotation = "varimax",  show.comm = TRUE, nmbr.fctr = 4, 
       method="ml", 
       var.labels = c("Organizational Capacity",
                      "Organizational Experience",
                      "Mobilization Capacity",
                      "Materiality Index",
                      "Sectoral Structural Power 1",
                      "Sectoral Structural Power 2",
                      "Sectoral Structural Power 3",
                      "General Structural Power",
                      "Links with Settler Organizations",
                      "Links with Indigenous Organizations",
                      "Links with Peasant Organizations",
                      "Influence on Government",
                      "Union Participation in Public Policies",
                      "Government Legitimation of Unionism",
                      "Government Responses to Union Demands"),
       title = "Factor analysis")


Politica.scores<- factor.scores(sub.base, varimax.factors ,
                                method="Thurstone")



base.labor <- cbind(base.labor, Politica.scores$scores)

options(max.print = 9999)


base.labor$Poder.Estructural = base.labor$ML1
base.labor$Poder.Asociativo = base.labor$ML4
base.labor$Poder.Social = base.labor$ML3
base.labor$Poder.Institucional = base.labor$ML2


# 7. Correlations --------------------------------------------------------------


library(corrr)
library(Hmisc) 
library(kableExtra) 




# Select variables

base_cor <- subset(base.labor, select = c(Poder_Asociativo, Poder_Estructural,
                                          Poder_Inst, poder_social, K5_idh,  
                                          K3_ginipost, K7_libdem))




cor_matrix <- rcorr(as.matrix(base_cor), type = "pearson")
cor_df <- cor_matrix$r  # Matriz de correlaciones
p_values <- cor_matrix$P  # Matriz de p-valores


add_stars <- function(r, p) {
  ifelse(p < 0.001, paste0(round(r, 3), "***"),
         ifelse(p < 0.01, paste0(round(r, 3), "**"),
                ifelse(p < 0.05, paste0(round(r, 3), "*"),
                       round(r, 3))))
}


cor_starred <- matrix(mapply(add_stars, cor_df, p_values), 
                      nrow = nrow(cor_df), ncol = ncol(cor_df),
                      dimnames = list(colnames(base_cor), colnames(base_cor)))


cor_table <- as.data.frame(cor_starred)
cor_table[upper.tri(cor_table)] <- ""  # Dejar vacía la parte superior para mejor lectura


kable(cor_table, format = "html", caption = "Matriz de Correlaciones con Significancia",
      align = "c") %>% kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = F)




base_cor=subset(base.labor, select=c(Poder_Asociativo , Poder_Estructural,
                                     Poder_Inst, poder_social, Poder.Asociativo, Poder.Estructural,
                                     Poder.Institucional, Poder.Social))


df=base_cor %>% 
  correlate(diagonal = 1) %>%
  shave(upper = TRUE) 

fashion(df)


# 8. Hierarchical clustering  ---------------------------------------------------


library(dplyr)
mydata=base.labor%>%group_by(pais)%>%dplyr::summarize(Poder.Institucional=mean(Poder.Institucional, na.rm=TRUE), 
                                        Poder.Social=mean(Poder.Social, na.rm=TRUE), 
                                        Poder.Asociativo= mean(Poder.Asociativo, na.rm=TRUE), 
                                        Poder.Estructural=mean (Poder.Estructural, na.rm=TRUE))


# Ward Hierarchical Clustering
mydata
mydata=as.data.frame(mydata)
rownames(mydata) <- mydata$pais
mydata
mydata$PAIS=NULL
d <- dist(mydata, method = "euclidean") # distance matrix
fit <- hclust(d, method="ward.D") 
plot(fit) # display dendogram
groups <- cutree(fit, k=4) # cut tree into 4 clusters
# draw dendogram with red borders around the 4 clusters 
rect.hclust(fit, k=4, border="red")


#Alterative

library("cluster")
library("factoextra")
library("magrittr")


# Compute hierarchical clustering
res.hc <- mydata %>%
  dist(method = "euclidean") %>% # Compute dissimilarity matrix
  hclust(method = "ward.D2")     # Compute hierachical clustering


# Visualize using factoextra
# Cut in 4 groups and color by groups
fviz_dend(res.hc, k = 4, # Cut in four groups
          cex = 0.8, # label size
          k_colors = c("#2E9FDF", "#00AFBB", "#E7B800"),
          color_labels_by_k = FALSE, # color labels by groups
          rect = TRUE, # Add rectangle around groups,
          type = c("rectangle"),
          ggtheme = theme_classic())




cutree(fit,k=4)

factor(groups)
mydata$grupos <- factor(groups)
mydata


base.labor$cluster=NA
base.labor$cluster[base.labor$pais=="Argentina" |
                     base.labor$pais == "Uruguay" ]= 1

base.labor$cluster[base.labor$pais=="Bolivia"|   base.labor$pais == "Panamá"|
                     base.labor$pais == "Paraguay" | 
                     base.labor$pais=="Guatemala" |
                     base.labor$pais == "Honduras" |
                     base.labor$pais == "Ecuador"]= 2

base.labor$cluster[ base.labor$pais=="México"| 
                      base.labor$pais=="Chile" | 
                      base.labor$pais=="Brasil" ]= 3
                   
base.labor$cluster[base.labor$pais=="Costa Rica"|base.labor$pais=="Colombia" | 
                     base.labor$pais=="El Salvador" | 
                     base.labor$pais== "Nicaragua"  | 
                    base.labor$pais=="Perú" | base.labor$pais== "Venezuela"  ]= 4


table(base.labor$cluster)

#par(mfrow = c(2, 3))



# 9. Analysis of the different clusters ---------------------------------------



base.labor$Poder.Asociativo.st=normalize_min_max(base.labor$Poder.Asociativo)
base.labor$Poder.Social.st=normalize_min_max(base.labor$Poder.Social)
base.labor$Poder.Institucional.st=normalize_min_max(base.labor$Poder.Institucional)
base.labor$Poder.Estructural.st=normalize_min_max(base.labor$Poder.Estructural)



mydata=subset(base.labor, select = c( Poder_Asociativo , Poder_Estructural,
                                      Poder_Inst, poder_social, cluster)) 
mydata <- na.omit(mydata) # listwise deletion of missing
mydata
datos.cluster= mydata %>% group_by(cluster)%>% 
  dplyr::summarize(Poder.Institucional=mean(Poder_Inst, na.rm=TRUE),
            Poder.Social=mean(poder_social, na.rm=TRUE),
            Poder.Estructural=mean(Poder_Estructural, na.rm=TRUE),
            Poder.Asociativo=mean( Poder_Asociativo, na.rm=TRUE))
datos.cluster

datos.cluster$Group.1= factor(datos.cluster$cluster, 
                              levels = c(1,2,3,4),
                              labels = c("Fuerte", "Movimental","Corporativo", "Débil"))
datos.cluster <- datos.cluster[c(-1)] 
datos.cluster

library(reshape2)
means.long<-melt(datos.cluster,id.vars=c("Group.1"))
means.long

library(ggthemes) # Para temas adicionales y paletas de colores


p <- ggplot(means.long, aes(x=Group.1, y=value, fill=factor(variable))) +
  geom_bar(stat="identity", position="dodge", width=0.7) + # Reduce el ancho para mejor visibilidad
  scale_fill_manual(values=c("#4E79A7", "#F28E2B", "#76B7B2", "#E15759"), 
                    name="Tipo de Poder",
                    labels=c("Institucional", "Social", "Estructural", "Asociativo")) +
  labs(title="Distribución de Poderes en Diferentes clusters",
       subtitle="Comparación de distintos tipos de poder sindical",
       x="",
       y="Standarized values") +
  theme_minimal(base_family="Arial") +  
  theme(plot.title=element_text(face="bold", hjust=0.5, size=16), # Título más grande y centrado
        plot.subtitle=element_text(hjust=0.5, size=12), # Subtítulo más claro
        axis.text.x=element_text(angle=0, hjust=0.5, size=12), 
        axis.text.y=element_text(size=14), # Agrandar etiquetas del eje Y
        legend.title=element_text(face="bold", size=12), 
        legend.text=element_text(size=11),
        legend.position="top")  # Mueve la leyenda abajo para mejor distribución

print(p)


# 10. Analysis of the evolution of the different power resources ----------------

tabla <- base.labor %>%
  dplyr::group_by(anio) %>%
  dplyr::summarise(
    Poder_Inst = mean(Poder_Inst, na.rm = TRUE), 
    Poder_Social = mean(poder_social, na.rm = TRUE),
    Poder_Asociativo = mean(Poder_Asociativo, na.rm = TRUE),
    Poder_Estructural = mean(Poder_Estructural, na.rm = TRUE)
  )

# Definir colores sobrios y elegantes
colores_academicos <- c("Poder Institucional" = "#264653",  # Azul oscuro elegante
                        "Poder Social" = "#E76F51",        # Rojo terracota
                        "Poder Asociativo" = "#2A9D8F",    # Verde agua sobrio
                        "Poder Estructural" = "#D4A373")   # Marrón suave

# Crear el gráfico
ggplot(tabla, aes(x = anio)) +
  geom_smooth(aes(y = Poder_Inst, colour = "Poder Institucional"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.5) +
  geom_smooth(aes(y = Poder_Social, colour = "Poder Social"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.5) +
  geom_smooth(aes(y = Poder_Asociativo, colour = "Poder Asociativo"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.5) +
  geom_smooth(aes(y = Poder_Estructural, colour = "Poder Estructural"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.5) +
  scale_color_manual(values = colores_academicos) +
  labs(
    title = "Evolución de los Poderes Sindicales en América Latina",
    subtitle = "Análisis de tendencias de poder institucional, social, asociativo y estructural",
    y = "Puntaje estandarizado",
    x = "Año"
  ) +
  theme_minimal(base_size = 16, base_family = "Arial") +
  theme(
    plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5, size = 14, color = "grey40"),
    axis.text.x = element_text(angle = 0, vjust = 0.5, size = 14),
    axis.text.y = element_text(size = 14),
    legend.position = "top",
    legend.title = element_blank(),
    legend.text = element_text(size = 14),
    panel.grid.major.y = element_line(color = "grey85"),
    panel.grid.minor = element_blank() )




tabla <- base.labor %>%
  dplyr::group_by(anio, pais) %>%
  dplyr::summarise(
    Poder_Inst = mean(Poder_Inst, na.rm = TRUE), 
    Poder_Social = mean(poder_social, na.rm = TRUE),
    Poder_Asociativo = mean(Poder_Asociativo, na.rm = TRUE),
    Poder_Estructural = mean(Poder_Estructural, na.rm = TRUE)
  )

# Definir colores sobrios y elegantes
colores_academicos <- c("Poder Institucional" = "#264653",  # Azul oscuro sobrio
                        "Poder Social" = "#E76F51",        # Rojo terracota
                        "Poder Asociativo" = "#2A9D8F",    # Verde elegante
                        "Poder Estructural" = "#D4A373")   # Beige/marrón suave

# Crear el gráfico
ggplot(tabla, aes(x = anio)) +
  geom_smooth(aes(y = Poder_Inst, colour = "Poder Institucional"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.2) +
  geom_smooth(aes(y = Poder_Social, colour = "Poder Social"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.2) +
  geom_smooth(aes(y = Poder_Asociativo, colour = "Poder Asociativo"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.2) +
  geom_smooth(aes(y = Poder_Estructural, colour = "Poder Estructural"), method = "loess", 
              se = FALSE, span = 0.3, size = 1.2) +
  scale_color_manual(values = colores_academicos) +
  labs(
    title = "Evolución de los Poderes Sindicales en América Latina",
    subtitle = "Tendencias de poder institucional, social, asociativo y estructural por país",
    y = "Puntaje estandarizado",
    x = "Año"
  ) +
  theme_minimal(base_size = 16, base_family = "Arial") +
  theme(
    plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5, size = 14, color = "grey40"),
    axis.text.x = element_text(angle = 45, hjust = 1, size = 12),
    axis.text.y = element_text(size = 12),
    legend.position = "top",
    legend.title = element_blank(),
    legend.text = element_text(size = 14),
    panel.grid.major = element_line(color = "grey80"),
    panel.grid.minor = element_blank()
  ) +
  facet_wrap(~pais)  



# 10. Analysis of the distribution of the different power resources ----------------


# Procesamiento de datos
base <- base.labor %>%
  dplyr::group_by(pais) %>%
  dplyr::summarise(
    Poder_institucional = mean(Poder_Inst, na.rm = TRUE),
    Poder_estructural = mean(Poder_Estructural, na.rm = TRUE),
    Poder_asociativo = mean(Poder_Asociativo, na.rm = TRUE),
    Poder_social = mean(poder_social, na.rm = TRUE)
  )

data_long <- tidyr::gather(base, condition, measurement, Poder_institucional:Poder_social, factor_key = TRUE)

# Definir colores académicos sobrios
colores_academicos <- c("Poder_institucional" = "#264653",  # Azul oscuro elegante
                        "Poder_estructural" = "#D4A373",    # Marrón suave
                        "Poder_asociativo" = "#2A9D8F",    # Verde agua sobrio
                        "Poder_social" = "#E76F51")        # Rojo terracota

# Crear el gráfico mejorado
pl1 <- ggplot(data = data_long, aes(x = reorder(pais, -measurement), y = measurement, fill = condition)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +  # Espaciado entre barras
  scale_fill_manual(values = colores_academicos, labels = c("Poder Institucional", "Poder Estructural", "Poder Asociativo", "Poder Social")) +
  labs(
    title = "Distribución del Poder Sindical en América Latina (1990-2020)",
    subtitle = "Promedios por país y tipo de poder",
    x = "",
    y = "Poder sindical promedio"
  ) +
  theme_minimal(base_size = 16, base_family = "Arial") +
  theme(
    plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5, size = 14, color = "grey40"),
    axis.text.x = element_text(angle = 45, hjust = 1, size = 14),
    axis.text.y = element_text(size = 14),
    legend.position = "top",
    legend.title = element_blank(),
    legend.text = element_text(size = 14),
    panel.grid.major.y = element_line(color = "grey85"),
    panel.grid.minor = element_blank()
  )

print(pl1)





